package indi.zhifa.core.auth.filter;

import indi.zhifa.core.auth.entity.RequireRole;
import indi.zhifa.core.auth.interfaces.IAuthObject;
import indi.zhifa.core.auth.util.ITokenUtil;
import indi.zhifa.core.common.web.entity.exception.ServiceException;
import lombok.RequiredArgsConstructor;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

@RequiredArgsConstructor
@Component
@Aspect
public class RoleRequireAop {

    private final ITokenUtil mTokenUtil;

    @Before("@annotation(pRequireRole)")
    public void doBefore(final JoinPoint joinPoint, final RequireRole pRequireRole) {
        if(!mTokenUtil.hasTokenObject()){
            return;
        }
        IAuthObject authObject = mTokenUtil.getAuthObject();
        List<String> roles = authObject.getRoles();
        Set<String> roleSet = new HashSet<>(roles);
        if(!roleSet.contains(pRequireRole.value())){
            throw new ServiceException("该接口只对角色"+ (StringUtils.hasText(pRequireRole.roleName()) ? pRequireRole.roleName(): pRequireRole.value())+"开放");
        }
    }

}
